#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <p89lpc9351.h>

#define LCD_RS  P1_2
#define LCD_R_W P1_3
#define LCD_E   P1_4

#define LCD_CLEAR 	0x01
#define LCD_HOME 	0x02
#define LCD_CURSOR 	0x80

void delay(int t)
{
    int j, k;
    for(j=0; j<700; j++)
    {
        for(k=0; k<t; k++);
    }
}

/**********************************************************/ 
void command(char i) 
{
	P0 = i; //put data on output Port 
	LCD_RS =0; //D/I=LOW : send instruction 
	LCD_R_W =0; //R/W=LOW : Write 
	LCD_E = 1; 
	delay(1); //enable pulse width >= 300ns 
	LCD_E = 0; //Clock enable: falling edge 
} 
/**********************************************************/ 
void write(char i) 
{ 
	P0 = i; //put data on output Port 
	LCD_RS =1; //D/I=LOW : send data 
	LCD_R_W =0; //R/W=LOW : Write 
	LCD_E = 1; 
	delay(1); //enable pulse width >= 300ns 
	LCD_E = 0; //Clock enable: falling edge 
} 
/**********************************************************/ 
void init() 
{ 
	LCD_E = 0; 
	delay(100); //Wait >15 msec after power is applied 
	command(0x30); //command 0x30 = Wake up 
	delay(30); //must wait 5ms, busy flag not available 
	command(0x30); //command 0x30 = Wake up #2 
	delay(10); //must wait 160us, busy flag not available 
	command(0x30); //command 0x30 = Wake up #3 
	delay(10); //must wait 160us, busy flag not available 
	command(0x38); //Function set: 8-bit/2-line 
	command(0x10); //Set cursor 
	command(0x0c); //Display ON; Cursor ON 
	command(0x06); //Entry mode set
	
	
} 
/**********************************************************/

void setLcdCursor(int row, int col)
{
	command(LCD_CURSOR | (col + row*40));
}

void writeString(char* c)
{
	while (*c)
		write(*c++);
}

void main (void)
{
	P0M1=0;
	P0M2=0;
	P1M1=0;
	P1M2=0;
	
	init();

	while (1)
	{
		command(LCD_CLEAR);
		command(LCD_HOME);
		
		writeString("test");
		delay(1);
	}
}